import cv2
import matplotlib.pyplot as plt

# 读取图像
img1 = cv2.imread("Text.png", 0)

# 二值化处理（0：黑；255：白）
for i in range(364):
    for j in range(1108):
        if img1[i, j] == 255:
            img1[i, j] = 255
        else:
            img1[i, j] = 0

img2 = img1.copy()
img3 = img1.copy()
img4 = cv2.copyMakeBorder(img1, 1, 1, 1, 1, cv2.BORDER_REFLECT) # 上下左右各扩充1，复制最近像素

# 腐蚀
for i in range(1,365):
    for j in range(1,1109):
        if img4[i, j]==0 and img4[i - 1, j - 1]==0 and img4[i - 1, j]==0 and img4[i - 1, j + 1]==0 and img4[i, j - 1]==0 and img4[i, j + 1]==0 and img4[i + 1, j - 1]==0 and img4[i + 1, j]==0 and img4[i + 1, j + 1]==0:
            img2[i-1,j-1] = 0
        else:
            img2[i-1,j-1] = 255

# 膨胀
for i in range(1,365):
    for j in range(1,1109):
        if img4[i, j]==0 or img4[i - 1, j - 1]==0 or img4[i - 1, j]==0 or img4[i - 1, j + 1]==0 or img4[i, j - 1]==0 or img4[i, j + 1]==0 or img4[i + 1, j - 1]==0 or img4[i + 1, j]==0 or img4[i + 1, j + 1]==0:
            img3[i-1,j-1] = 0
        else:
            img3[i-1,j-1] = 255

# 显示图像
plt.figure(figsize=(10,4),dpi=120)
plt.subplot(131),plt.imshow(img1, cmap = 'gray')
plt.title('original'),plt.axis('off')
plt.subplot(132),plt.imshow(img2, cmap = 'gray')
plt.title('erode'), plt.axis('off')
plt.subplot(133),plt.imshow(img3, cmap = 'gray')
plt.title('dilate'), plt.axis('off')
plt.show()